﻿#include <iostream>
using namespace std;

void test1()
{
	string s("hello world");
	cout << s.max_size() << endl;
	//不能保证长度一定能达到max_size，大概率会在到达max_size之前申请空间失败
	try
	{
		s.reserve(s.max_size());
	}
	catch (const std::exception& e)
	{
		cout << e.what() << endl;
	}
}

void test2()
{
	string s;
	//s.reserve(500); reserve的价值是在知道使用空间大小时可以直接开辟出想要的空间，避免了频繁的扩容消耗

	//测试VS下的string扩容机制，一般是先匀速扩容后大约1.5倍扩容
	size_t old = s.capacity();
	cout << old << endl;

	for (int i = 0; i < 500; i++)
	{
		s.push_back('a');
		if (s.capacity() != old)
		{
			cout << s.capacity() << endl;
			old = s.capacity();
		}
	}
}

void test3()
{
	string s("aaaa");
	// n > capapcity 时，扩容到n甚至更大
	cout << s.capacity() << endl;
	s.reserve(111); //遵循内存对齐
	cout << s.capacity() << endl;

	//n < capacity 时，最多缩容到等于当前有效字符个数；也有可能不缩；不会影响有效数据
	s.reserve(5); //缩到15
	//s.reserve(3); //不缩
	//s.reserve(16); //不缩
	//特定数字才触发缩容，还要按它编译器内定的规则来缩
	cout << s.capacity() << endl;
}

void test4()
{
	string s("hello world");
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	cout << endl;

	//n > capacity时，扩容+填充
	s.resize(20, 'x');
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	cout << endl;

	//size < n <= capacity时，只填充
	s.resize(25, 'x');
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	cout << endl;

	//n < size时，size缩短到n，并删除长度大于n有效数据，不缩容
	s.resize(5, 'x');
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.capacity() << endl;
}

void test5()
{
	string s("hello world");
	string t("abcd");
	s.append(t, 0, string::npos);
	cout << s << endl;

	s += "abcd";
	s += 't';
	s += t;
	cout << s << endl;
	//insert erase push_back pop_back ...
}

void test6() {
	string s("hello world");
	s.resize(31);
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	s.resize(159); //给了159，开了159个空间，看来并不是每次都多开，而是遵循内存对齐
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	s.resize(50);
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	s.resize(10000);
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	s.resize(20);
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	s.resize(1);
	cout << s.size() << endl;
	cout << s.capacity() << endl;
}

int main()
{
	//test1();
	//test2();
	//test3();
	//test4();
	//test5();
	//test6();
	return 0;
}